﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Windows.Threading;
using System.Threading;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Media;

namespace AlgoLogicMessenger
{
    /// <summary>
    /// Interaction logic for QuestionAnswer.xaml
    /// </summary>
    public partial class QuestionAnswer : Page
    {
        private int MAXQNSCOUNT = -1;
        private int CURRENTQNSCOUNT = 1;

        public int seconds; // Seconds.
        public int minutes; // Minutes.
        public int hours;   // Hours.
        public bool paused; // State of the timer [PAUSED/WORKING].
        public bool stop; //Stop the timer
        public bool pauseFalse;
        public bool resumePause;
        public bool last5audioplay;

        string Qnum = null;
        string TotalQcount = null; //Total Question
        int qno = 0;
        string qnum = null;
        string qn = null;
        string CorrectAnswer = null;
        string TeamAns = null;
        string ans = null;
        string image = null;
        string A = null;
        string B = null;
        string C = null;
        string D = null;
        int m = 0;
        int s = 0;
        string fileName = "";
        string TeamN = null;
        string sI = null; //previewImage
        string QnsN = null; //@massConvo

        DispatcherTimer timer1 = new DispatcherTimer();

        Thread thread;
        bool IsThreadRunning = false;
        ReaderWriterLock rwl = new ReaderWriterLock();
        ArrayList userList = new ArrayList();
        SoundPlayer player = new SoundPlayer("C://Images//AlgoLogicAudio//5secwav.wav");
        SoundPlayer player4 = new SoundPlayer("C://Images//AlgoLogicAudio//4secwav.wav");
        SoundPlayer player3 = new SoundPlayer("C://Images//AlgoLogicAudio//3secwav.wav");
        SoundPlayer player2 = new SoundPlayer("C://Images//AlgoLogicAudio//2secwav.wav");
        SoundPlayer player1 = new SoundPlayer("C://Images//AlgoLogicAudio//1secwav.wav");


        //sockets
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        NetworkStream serverStream = default(NetworkStream);
        string readData = null;
        string massConvoReadData = null;

        //create competitor list
        List<Competitor> competitorList = new List<Competitor>();
        List<BitmapImage> imageList = new List<BitmapImage>();
        int ClickCount = 0;
        //string connstr = @"Data Source=.;Initial Catalog=AlgoLogicDatabase;Persist Security Info=True;User ID = sa; Password = imsa";
        string connstr = @"Data Source=.;Initial Catalog=AlgoLogicDB;Integrated Security=True";

        string quiz = "";
        int min = 0;
        int sec = 0;
        int qnNum = 0;
        string msgToCompetitors = null;
        string msgUpdateCompetitor = null;
        DateTime date = DateTime.Today;

        public QuestionAnswer()
        {
            InitializeComponent();
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Interval = new TimeSpan(0, 0, 1);

            string ip = IP.Address;

            clientSocket.Connect(IP.Address, 8888);
            serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes("" + "#");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            Thread ctThread = new Thread(getMessage);
            ctThread.Start();
        }

        private void BtnBack_Click(object sender, RoutedEventArgs e)
        {
            NavigationService nav = NavigationService.GetNavigationService(this);
            nav.Navigate(new System.Uri("NavigationPage.xaml", UriKind.RelativeOrAbsolute));

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes("@back|#");
            if (serverStream != null)
            {
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
            }
        }

        private void getMessage()
        {
            while (true)
            {
                try
                {
                    serverStream = clientSocket.GetStream();
                    int bufferSize = clientSocket.ReceiveBufferSize;
                    //byte[] inStream = new byte[65536];
                    byte[] inStream = new byte[bufferSize];
                    serverStream.Read(inStream, 0, bufferSize);
                    string returndata = System.Text.Encoding.ASCII.GetString(inStream);

                    //filter type of msg
                    string[] filterMsgType = returndata.Split('|');
                    string str = System.Text.Encoding.ASCII.GetString(inStream, 0, inStream.Length);
                    str = str.Replace("\0", "");
                    string[] array1 = str.Split('|');

                    if (filterMsgType[1] == "TeamCreated!")
                    {
                        returndata = filterMsgType[0].ToString() + " has connected!";
                    }
                    else if (str.StartsWith("@massConvo"))
                    {
                        //returndata = array1[1].ToString() + ": " + array1[2].ToString() + Environment.NewLine + "Time Left: " + array1[3].ToString() + " Seconds" + Environment.NewLine;
                        returndata = array1[1].ToString() + ": " + array1[2].ToString() + Environment.NewLine;
                        //validate against database the answer.

                        SqlConnection conn = new SqlConnection(connstr); //1st
                        conn.Open();
                        SqlDataAdapter da = new SqlDataAdapter();
                        da.SelectCommand = new SqlCommand("SELECT Answer FROM Export WHERE QuizNum=@QuizNum", conn);
                        da.SelectCommand.Parameters.AddWithValue("@QuizNum", qnum);
                        SqlDataReader dr = da.SelectCommand.ExecuteReader();
                        while (dr.Read())
                        {
                            CorrectAnswer = dr["Answer"].ToString();
                        }
                        dr.Close();

                        if (string.Equals(CorrectAnswer, array1[2].ToString(), StringComparison.CurrentCultureIgnoreCase))
                        {
                            da.SelectCommand = new SqlCommand("IF(select TeamName from Result where QuizNum=@QuizNum and Score=1) is null select 'Fastest'", conn);
                            da.SelectCommand.Parameters.AddWithValue("@QuizNum", qnum);
                            da.SelectCommand.ExecuteNonQuery();
                            SqlDataReader dr2 = da.SelectCommand.ExecuteReader();
                            if (dr2.HasRows) //check if others have answered correctly already
                            {
                                dr2.Close();
                                da.SelectCommand = new SqlCommand("INSERT INTO Result (TeamName,Score,Time,QuizNum,Answer,Date)Values(@TeamName,@Score,@Time,@QuizNum,@Answer,@Date)", conn);
                                da.SelectCommand.Parameters.AddWithValue("@TeamName", array1[1].ToString());
                                da.SelectCommand.Parameters.AddWithValue("@Score", '1');
                                da.SelectCommand.Parameters.AddWithValue("@Time", array1[3].ToString());
                                da.SelectCommand.Parameters.AddWithValue("@QuizNum", qnum);
                                da.SelectCommand.Parameters.AddWithValue("@Answer", array1[2].ToString());
                                da.SelectCommand.Parameters.AddWithValue("@Date", date);
                                da.SelectCommand.ExecuteNonQuery();
                            }

                            else
                            {
                                dr2.Close();
                                da.SelectCommand = new SqlCommand("INSERT INTO Result (TeamName,Score,Time,QuizNum,Answer,Date)Values(@TeamName,@Score,@Time,@QuizNum,@Answer,@Date)", conn);
                                da.SelectCommand.Parameters.AddWithValue("@TeamName", array1[1].ToString());
                                da.SelectCommand.Parameters.AddWithValue("@Score", '0');
                                da.SelectCommand.Parameters.AddWithValue("@Time", array1[3].ToString());
                                da.SelectCommand.Parameters.AddWithValue("@QuizNum", qnum);
                                da.SelectCommand.Parameters.AddWithValue("@Answer", array1[2].ToString());
                                da.SelectCommand.Parameters.AddWithValue("@Date", date);
                                da.SelectCommand.ExecuteNonQuery();
                            }
                        }

                        else
                        {
                            da.SelectCommand = new SqlCommand("INSERT INTO Result (TeamName,Score,Time,QuizNum,Answer,Date)Values(@TeamName,@Score,@Time,@QuizNum,@Answer,@Date)", conn);
                            da.SelectCommand.Parameters.AddWithValue("@TeamName", array1[1].ToString());
                            da.SelectCommand.Parameters.AddWithValue("@Score", '0');
                            da.SelectCommand.Parameters.AddWithValue("@Time", array1[3].ToString());
                            da.SelectCommand.Parameters.AddWithValue("@QuizNum", qnum);
                            da.SelectCommand.Parameters.AddWithValue("@Answer", array1[2].ToString());
                            da.SelectCommand.Parameters.AddWithValue("@Date", date);
                            da.SelectCommand.ExecuteNonQuery();
                        }

                        conn.Close();
                        readData = "" + returndata;
                        msgTalk();
                    }
                    if (str.StartsWith("@EndComConv"))
                    {
                        returndata = array1[1].ToString() + ": " + array1[2].ToString() + Environment.NewLine;
                    }
                    //else if (str.StartsWith("@faster"))
                    //{
                    //    if (array1[1].ToString() != "")
                    //    {
                    //        if (array1[1].Contains("@Score"))
                    //        {
                    //            array1[1].Replace("@Score", "");
                    //        }
                    //        returndata = array1[1].ToString() + ", " + " Scored 1 Point!" + Environment.NewLine;
                    //    }
                    //    else
                    //    {
                    //        returndata = "None of the Team Scored!" + Environment.NewLine;
                    //    }
                    //    readData = "" + returndata;
                    //    msg();
                    //}
                    else if (filterMsgType[1] == "NameUsed!")
                    {
                        returndata = "";
                    }
                    else if (str.StartsWith("@SendToComp"))
                    {
                        returndata = array1[1].ToString() + ": " + array1[2].ToString() + Environment.NewLine;
                        readData = returndata;
                        msgTalk();
                    }
                    else if (str.StartsWith("@comConv"))
                    {
                        returndata = array1[1].ToString() + ": " + array1[2].ToString() + Environment.NewLine;
                        readData = returndata;
                        msgTalk();
                    }
                    else if (str.StartsWith("@comAnsConv"))
                    {
                        returndata = "[" + array1[3] + "]" + array1[4].ToString() + Environment.NewLine;
                        readData = "" + returndata;
                        msgTalk();
                    }
                    else if (str.StartsWith("@displayTime"))
                    {
                        returndata = "";
                        readData = "" + returndata;
                        displayTime();
                    }
                    else if (str.StartsWith("@time"))
                    {
                        returndata = "";
                        readData = "" + returndata;
                        msgTalk();
                    }
                    else if (str.StartsWith("@pause"))
                    {
                        returndata = "";
                    }
                    else if (str.StartsWith("@resumePause"))
                    {
                        returndata = "";
                    }
                    else if (str.StartsWith("@stop"))
                    {
                        returndata = "";
                    }
                    else if (str.StartsWith("@logout"))
                    {
                        returndata = array1[1].ToString() + " Has Logout." + Environment.NewLine;
                    }
                    else if (str.StartsWith("@back"))
                    {
                        returndata = "";
                    }
                    else if (str.StartsWith("@Score"))
                    {
                        returndata = "";
                    }
                    else if (str.StartsWith("@AllowNavigation"))
                    {
                        returndata = "";
                    }
                    else if (str.StartsWith("@DisallowNavigation"))
                    {
                        returndata = "";
                    }
                    else if (str.StartsWith("@Talk")) //Chat (facilitator)
                    {
                        returndata = "Facilitator: " + array1[1] + Environment.NewLine;
                        readData = "" + returndata;
                        msgTalk();
                    }
                    else if (str.StartsWith("@talkConvo")) //Chat (competitor)
                    {
                        returndata = array1[1].ToString() + ": " + array1[2].ToString() + Environment.NewLine;
                        readData = "" + returndata; //readData is = "Facilitator: (foul language)"
                        msgTalk();
                    }

                    else if (str.StartsWith("@startFacilTimer"))
                    {
                        //delay time 4 seconds before start
                        Thread.Sleep(4000);
                        timer1.Start();

                        byte[] outStream4 = System.Text.Encoding.ASCII.GetBytes(msgToCompetitors + "#");
                        if (serverStream != null)
                        {
                            serverStream.Write(outStream4, 0, outStream4.Length);
                            serverStream.Flush();
                        }

                        byte[] outStream = System.Text.Encoding.ASCII.GetBytes("@time|" + min + "|" + sec + "#");
                        if (serverStream != null)
                        {
                            serverStream.Write(outStream, 0, outStream.Length);
                            serverStream.Flush();
                        }
                    }

                    else if (str.StartsWith("@checkVulgar"))
                    {
                        bool containsVulgar = false;
                        List<String> vulgarList = new List<String>();
                        char[] vulgarArray = null;

                        try
                        {
                            SqlConnection conn = new SqlConnection(connstr);
                            conn.Open();
                            SqlCommand comm = new SqlCommand();
                            comm.Connection = conn;
                            comm.CommandText = "SELECT words from Profanity";
                            SqlDataReader dr = comm.ExecuteReader();
                            while (dr.Read())
                            {
                                vulgarList.Add(dr["words"].ToString());
                            }
                            dr.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Unable to establish connection to database");
                        }

                        finally
                        {
                            if (vulgarList.Count != 0)
                            {
                                foreach (String vulgar in vulgarList)
                                {
                                    vulgarArray = str.ToCharArray();
                                    for (int i = 0; i < vulgarArray.Length; i++)
                                    {
                                        //vulgarArray[i] is from str = what i have typed
                                        //eg if S == S, have to make it lowercase
                                        if (vulgarArray[i] == char.ToUpper(vulgarArray[i]))
                                        {
                                            vulgarArray[i] = char.ToLower(vulgarArray[i]);
                                        }
                                    }
                                    String vulgarString = new String(vulgarArray); //convert the array back to String for checking
                                    if (vulgarString.Contains(vulgar) == true)
                                    {
                                        containsVulgar = true;
                                        break;
                                    }
                                }

                                if (containsVulgar == true)
                                {
                                    string msg = "@displayMsgBox|" + array1[1].ToString();
                                    byte[] outStream5 = System.Text.Encoding.ASCII.GetBytes(msg + "#");
                                    if (serverStream != null)
                                    {
                                        serverStream.Write(outStream5, 0, outStream5.Length);
                                        serverStream.Flush();
                                    }
                                }

                                else
                                {
                                    string msg = "@talkConvo|" + array1[1].ToString() + "|" + array1[2].ToString();
                                    byte[] outStream5 = System.Text.Encoding.ASCII.GetBytes(msg + "#");
                                    if (serverStream != null)
                                    {
                                        serverStream.Write(outStream5, 0, outStream5.Length);
                                        serverStream.Flush();
                                    }
                                }


                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void msgTalk() //Chat (facilitator)
        {
            if (this.Dispatcher.Thread == Thread.CurrentThread)
            {
                if (readData != null)
                {
                    if (readData != "")
                    {
                        textBox1.Text = textBox1.Text + Environment.NewLine + readData;
                        textBox1.SelectionStart = textBox1.Text.Length;
                        textBox1.ScrollToEnd();
                    }
                }
            }
            else
            {
                Dispatcher.Invoke(new Action(msgTalk));
            }
        }

        private string displayQuestion()
        {
            SqlConnection conn = null;
            conn = new SqlConnection(connstr);
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter();

                try
                {
                    SqlCommand query = new SqlCommand("SELECT DISTINCT(QuizNum) FROM Export", conn);
                    SqlDataReader dr = query.ExecuteReader();
                    if (dr.HasRows)
                    {
                    while (dr.Read())
                    {
                        TotalQcount = dr["QuizNum"].ToString();
                    }
                    MAXQNSCOUNT = Convert.ToInt32(TotalQcount);
                    dr.Close();

                    if (cbQn.Items.Count < Convert.ToInt32(TotalQcount))
                    {
                        SqlCommand query1 = new SqlCommand("SELECT DISTINCT(QuizNum) FROM Export", conn);
                        SqlDataReader dr1 = query.ExecuteReader();                       
                            while (dr1.Read())
                            {
                                cbQn.Items.Add("Question " + dr1["QuizNum"]);
                            }
                            dr1.Close();
                            //1st Question
                            int qnno = 1;
                            qno = qnno;
                            da.SelectCommand = new SqlCommand("SELECT Question, Image, OptA, OptB, OptC, OptD FROM Export WHERE QuizNum=@qnum", conn);
                            da.SelectCommand.Parameters.AddWithValue("@qnum", qno);
                            SqlDataReader dr2 = da.SelectCommand.ExecuteReader();

                            while (dr2.Read())
                            {
                                lblQuiz.Content = "Question " + qno + ": ";
                                qn = dr2["Question"].ToString();
                                image = dr2["Image"].ToString();
                                A = dr2["OptA"].ToString();
                                B = dr2["OptB"].ToString();
                                C = dr2["OptC"].ToString();
                                D = dr2["OptD"].ToString();
                            }
                            dr2.Close();
                            BtnPrevious.IsEnabled = false;
                            BtnNext.IsEnabled = true;
                            msgToCompetitors = "@SendToComp|Facilitator|" + "Question " + qno + "|" + connstr + "|" + image + "|" + qn + "|" + A + "|" + B + "|" + C + "|" + D;
                        }
                        else
                        {
                            MessageBox.Show("Unable to establish connection to the database.");
                        }
                        PlayBtn.IsEnabled = true;
                    }

                    else
                    {
                        MessageBox.Show("There are no questions to be retrieved.");
                    }
                }

                catch (Exception ex)
                {
                    MessageBox.Show("Unable to establish connection to the database.");
                }

                finally
                {
                    MessageBox.Show(TotalQcount + " Questions have been retrieved successfully.");
                    btnLoadQuestions.IsEnabled = false;
                    conn.Close();
                }
            return qno.ToString();           
        }

        private string displayQuestionByComboBox() //combox box
        {
            SqlConnection conn = null;
            conn = new SqlConnection(connstr);
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter();

            try
            {
                if (cbQn.SelectedItem != null)
                {
                    string comboboxqn = cbQn.SelectedItem.ToString();
                    sI = comboboxqn.Remove(0, 9);
                    if (sI != qnum)
                    {
                        BitmapImage src = new BitmapImage();
                        string getim = null;
                        Qnum = cbQn.SelectedItem.ToString();
                        qnum = Qnum.Remove(0, 9).ToString();
                        conn = new SqlConnection(connstr);
                        conn.Open();

                        da.SelectCommand = new SqlCommand("SELECT QuizNum, Question, Image, OptA, OptB, OptC, OptD FROM Export WHERE QuizNum=@qnum", conn);
                        da.SelectCommand.Parameters.AddWithValue("@qnum", qnum);
                        SqlDataReader dr1 = da.SelectCommand.ExecuteReader();
                        while (dr1.Read())
                        {
                            qno = Convert.ToInt32(dr1["QuizNum"]);
                            lblQuiz.Content = "Question " + qnum + ": ";
                            qn = dr1["Question"].ToString();
                            image = dr1["Image"].ToString();
                            A = dr1["OptA"].ToString();
                            B = dr1["OptB"].ToString();
                            C = dr1["OptC"].ToString();
                            D = dr1["OptD"].ToString();
                        }
                        dr1.Close();

                        PlayBtn.IsEnabled = true;
                        CURRENTQNSCOUNT = Convert.ToInt32(qnum);
                        if (CURRENTQNSCOUNT == 1)
                        {
                            BtnPrevious.IsEnabled = false;
                            BtnNext.IsEnabled = true;
                        }
                        else if (CURRENTQNSCOUNT == MAXQNSCOUNT)
                        {
                            BtnNext.IsEnabled = false;
                            BtnPrevious.IsEnabled = true;
                            ClickCount = MAXQNSCOUNT - 1;
                        }
                        else
                        {
                            BtnPrevious.IsEnabled = true;
                            BtnNext.IsEnabled = true;
                            ClickCount = CURRENTQNSCOUNT;
                        }

                        msgUpdateCompetitor = "@UpdateComp|" + qnum;
                        byte[] outStream4 = System.Text.Encoding.ASCII.GetBytes(msgUpdateCompetitor + "#");
                        if (serverStream != null)
                        {
                            serverStream.Write(outStream4, 0, outStream4.Length);
                            serverStream.Flush();
                        }

                        msgToCompetitors = "@SendToComp|Facilitator|" + "Question " + qnum + "|" + connstr + "|" + image + "|" + qn + "|" + A + "|" + B + "|" + C + "|" + D;
                    }
                    else
                    {
                        MessageBox.Show(comboboxqn + " has already been selected.", "Notification", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }

                else
                {
                    MessageBox.Show("Please select a question.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
                Question.Text = "";
                LabA.Text = "A) ";
                LabB.Text = "B) ";
                LabC.Text = "C) ";
                LabD.Text = "D) ";
                imageoptA.Source = null;
                imageoptB.Source = null;
                imageoptC.Source = null;
                imageoptD.Source = null;
                imageppt.Source = null;
            }
            return qnum;
        }

        private void updateScore()
        {
            SqlConnection conn = new SqlConnection(connstr);
            conn.Open();
            try
            {
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = new SqlCommand("select TeamName, Sum(Score) AS Score from AlgoLogicDB.dbo.Result where Date=@date GROUP BY TeamName", conn);
                da1.SelectCommand.Parameters.AddWithValue("@date", date);
                SqlDataReader dr2 = da1.SelectCommand.ExecuteReader();

                while (dr2.Read())
                {
                    string TeamName = dr2["TeamName"].ToString();
                    int score = Convert.ToInt32(dr2["Score"]);

                    Thread.Sleep(100);
                    string msg2 = "@Score|" + TeamName + "|" + score;
                    byte[] outStream3 = System.Text.Encoding.ASCII.GetBytes(msg2 + "#");
                    if (serverStream != null)
                    {
                        serverStream.Write(outStream3, 0, outStream3.Length);
                        serverStream.Flush();
                    }
                }
                dr2.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to establish connection to the database.");
            }
            conn.Close();
        }

        private void displayAnswerBox()
        {
            SqlConnection conn = new SqlConnection(connstr);
            conn.Open();
            try
            {
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand("SELECT Answer FROM Export WHERE QuizNum=@QNum", conn);
                da.SelectCommand.Parameters.AddWithValue("@Qnum", qnum);
                SqlDataReader dr = da.SelectCommand.ExecuteReader();
                while (dr.Read())
                {
                    correctAns = dr["Answer"].ToString();

                }
                dr.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to establish connection to the database.");
            }
            conn.Close();

            string msg = "@comAnsConv|Question|" + connstr + "|" + "Question " + qnum + "|" + Environment.NewLine + "Answer: " + correctAns + "|" + correctAns;
            byte[] outStream2 = System.Text.Encoding.ASCII.GetBytes(msg + "#");
            if (serverStream != null)
            {
                serverStream.Write(outStream2, 0, outStream2.Length);
                serverStream.Flush();
            }
        }

        private int[] Preview_Time(string qnum)
        {
            int[] time = new int[2];

            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connstr);
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand("SELECT Min, Sec FROM Export where QuizNum = @qnum", conn);
                da.SelectCommand.Parameters.AddWithValue("@qnum", qnum);
                SqlDataReader dr = da.SelectCommand.ExecuteReader();
                while (dr.Read())
                {
                    time[0] = Convert.ToInt32(dr["Min"]);
                    time[1] = Convert.ToInt32(dr["Sec"]);
                }

                String t = "";
                String t2 = "";


                if (time[0] < 10)
                {
                    t = "0" + time[0];

                }
                else
                {
                    t = time[0].ToString();
                }

                if (time[1] < 10)
                {
                    t2 = "0" + time[1];

                }
                else
                {
                    t2 = time[1].ToString();
                }

                min = time[0];
                sec = time[1];
                lblMin.Content = t;
                lblSec.Content = t2;

                sMin.Content = t;
                sSec.Content = t2;
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes("@displayTime|" + t + "|" + t2 + "#");
                if (serverStream != null)
                {
                    serverStream.Write(outStream, 0, outStream.Length);
                    serverStream.Flush();
                }
                return time;

            }
            catch
            {
                return null;
            }
            finally
            {

                conn.Close();
            }
        }
        //Time
        private void timer1_Tick(object sender, EventArgs e)
        {
            // Verify if the time didn't pass.
            if ((minutes == 0) && (seconds == 0))
            {
                // If the time is over, clear all settings and fields.
                // Also, show the message, notifying that the time is over.
                timer1.Stop();
                BtnNext.IsEnabled = false;
                BtnPrevious.IsEnabled = false;
                btnOpen2.IsEnabled = false;
                PlayBtn.IsEnabled = false;
                PauseBtn.IsEnabled = false;

                lblMin.Content = "00";
                lblSec.Content = "00";

                btnA.IsEnabled = true;
                StopBtn.IsEnabled = false;
                StopBtn_Click(this, new RoutedEventArgs());               
            }
            else
            {
                // Else continue counting.
                if (seconds < 1)
                {
                    seconds = 59;
                    if (minutes == 0)
                    {
                        minutes = 59;
                    }
                    else
                    {
                        minutes -= 1;
                    }
                }
                else
                    seconds -= 1;
                // Display the current values of hours, minutes and seconds in
                // the corresponding fields.
                if (minutes < 10)
                {
                    lblMin.Content = "0" + minutes.ToString();
                }
                else
                {
                    lblMin.Content = minutes.ToString();
                }
                if (seconds < 10)
                {
                    lblSec.Content = "0" + seconds.ToString();
                }
                else
                {
                    lblSec.Content = seconds.ToString();
                }

                if (Convert.ToInt32(lblMin.Content) == 00)
                {
                    if (Convert.ToInt32(lblSec.Content) == 01)
                    {
                        player1.Play();
                    }

                    if (Convert.ToInt32(lblSec.Content) == 02)
                    {
                        player2.Play();
                    }

                    if (Convert.ToInt32(lblSec.Content) == 03)
                    {
                        player3.Play();
                    }

                    if (Convert.ToInt32(lblSec.Content) == 04)
                    {
                        player4.Play();
                    }

                    if (Convert.ToInt32(lblSec.Content) == 05)
                    {
                        player.Play();
                        last5audioplay = true;
                    }
                }

                BtnNext.IsEnabled = false;
                BtnPrevious.IsEnabled = false;
                btnOpen2.IsEnabled = false;
            }
        }

        private void displayTime()
        {
            if (this.Dispatcher.Thread == Thread.CurrentThread)
            {
                if (readData != null)
                {
                    if (readData != "")
                    {
                        lblMin.Content = readData;
                        lblSec.Content = readData;
                    }
                }
            }
            else
            {
                Dispatcher.Invoke(new Action(displayTime));
            }
        }

        int AnsCount = 1;
        string correctAns = "";

        private void btnA_Click(object sender, RoutedEventArgs e) //click on answer button
        {
            SqlConnection conn = new SqlConnection(connstr);
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter();

            btnOpen2.IsEnabled = true;
            BtnNext.IsEnabled = true;
            BtnPrevious.IsEnabled = true;
            BtnScore.IsEnabled = true;
            lblMin.Content = "00";
            lblSec.Content = "00";
            DateTime date = DateTime.Today;

            if (Convert.ToInt32(qnum) == 1)
            {
                BtnNext.IsEnabled = true;
                BtnPrevious.IsEnabled = false;
            }
            else if (qnum == TotalQcount)
            {
                BtnPrevious.IsEnabled = true;
                BtnNext.IsEnabled = false;
            }
            btnA.IsEnabled = false;

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes("@time|" + lblMin.Content + "|" + lblSec.Content + "#");
            if (serverStream != null)
            {
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
            }

            displayAnswerBox();
            //visible of message box
        }

        private void BtnNext_Click(object sender, RoutedEventArgs e)
        {
            BtnPrevious.IsEnabled = true;
            PlayBtn.IsEnabled = true;
            CURRENTQNSCOUNT++;
            Preview_Time(CURRENTQNSCOUNT.ToString());
            ClickCount++;
            qnum = CURRENTQNSCOUNT.ToString();

            SqlConnection conn = null;
            if (Convert.ToInt32(qnum) == Convert.ToInt32(TotalQcount))
            {
                conn = new SqlConnection(connstr);
                conn.Open();
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = new SqlCommand("SELECT Question, Image, OptA, OptB, OptC, OptD FROM Export WHERE QuizNum=@qnum", conn);
                SqlParameter QNum = new SqlParameter();
                da1.SelectCommand.Parameters.AddWithValue("@qnum", TotalQcount);
                SqlDataReader dr1 = da1.SelectCommand.ExecuteReader();

                while (dr1.Read())
                {
                    lblQuiz.Content = "Question " + TotalQcount + ": ";
                    qn = dr1["Question"].ToString();
                    image = dr1["Image"].ToString();
                    A = dr1["OptA"].ToString();
                    B = dr1["OptB"].ToString();
                    C = dr1["OptC"].ToString();
                    D = dr1["OptD"].ToString();
                }
                dr1.Close();
                BtnNext.IsEnabled = false;
            }
            else if (Convert.ToInt32(qnum) < Convert.ToInt32(TotalQcount))
            {
                BtnPrevious.IsEnabled = true;
                BtnNext.IsEnabled = true;

                conn = new SqlConnection(connstr);
                conn.Open();
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = new SqlCommand("SELECT Question, Image, OptA, OptB, OptC, OptD FROM Export WHERE QuizNum=@qnum", conn);
                SqlParameter QNum = new SqlParameter();
                da1.SelectCommand.Parameters.AddWithValue("@qnum", qnum);
                SqlDataReader dr1 = da1.SelectCommand.ExecuteReader();

                while (dr1.Read())
                {
                    lblQuiz.Content = "Question " + qnum + ": ";
                    qn = dr1["Question"].ToString();
                    image = dr1["Image"].ToString();
                    A = dr1["OptA"].ToString();
                    B = dr1["OptB"].ToString();
                    C = dr1["OptC"].ToString();
                    D = dr1["OptD"].ToString();
                }
                dr1.Close();
            }

            msgUpdateCompetitor = "@UpdateComp|" + qnum;
            byte[] outStream4 = System.Text.Encoding.ASCII.GetBytes(msgUpdateCompetitor + "#");
            if (serverStream != null)
            {
                serverStream.Write(outStream4, 0, outStream4.Length);
                serverStream.Flush();
            }

            msgToCompetitors = "@SendToComp|Facilitator|" + "Question " + qnum + "|" + connstr + "|" + image + "|" + qn + "|" + A + "|" + B + "|" + C + "|" + D;
            Question.Text = "";
            LabA.Text = "A) ";
            LabB.Text = "B) ";
            LabC.Text = "C) ";
            LabD.Text = "D) ";
            imageoptA.Source = null;
            imageoptB.Source = null;
            imageoptC.Source = null;
            imageoptD.Source = null;
            imageppt.Source = null;
            cbQn.SelectedIndex = cbQn.Items.IndexOf("Question " + qnum);
            updateScore();
        }

        private void BtnPrevious_Click(object sender, RoutedEventArgs e)
        {
            PlayBtn.IsEnabled = true;
            CURRENTQNSCOUNT--;
            Preview_Time(CURRENTQNSCOUNT.ToString());
            qnum = CURRENTQNSCOUNT.ToString();
            ClickCount--;
            SqlConnection conn = null;

            if (ClickCount == 0)
            {
                conn = new SqlConnection(connstr);
                conn.Open();
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = new SqlCommand("SELECT Question, Image, OptA, OptB, OptC, OptD FROM Export WHERE QuizNum=@qnum", conn);
                SqlParameter QNum = new SqlParameter();
                da1.SelectCommand.Parameters.AddWithValue("@qnum", qnum);
                SqlDataReader dr1 = da1.SelectCommand.ExecuteReader();

                while (dr1.Read())
                {
                    lblQuiz.Content = "Question " + qnum + ": ";
                    qn = dr1["Question"].ToString();
                    image = dr1["Image"].ToString();
                    A = dr1["OptA"].ToString();
                    B = dr1["OptB"].ToString();
                    C = dr1["OptC"].ToString();
                    D = dr1["OptD"].ToString();
                }
                dr1.Close();
                BtnNext.IsEnabled = true;
                BtnPrevious.IsEnabled = false;
            }
            if (ClickCount == 1)
            {
                conn = new SqlConnection(connstr);
                conn.Open();
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = new SqlCommand("SELECT Question, Image, OptA, OptB, OptC, OptD FROM Export WHERE QuizNum=@qnum", conn);
                SqlParameter QNum = new SqlParameter();
                da1.SelectCommand.Parameters.AddWithValue("@qnum", qnum);
                SqlDataReader dr1 = da1.SelectCommand.ExecuteReader();

                while (dr1.Read())
                {
                    lblQuiz.Content = "Question " + qnum + ": ";
                    qn = dr1["Question"].ToString();
                    image = dr1["Image"].ToString();
                    A = dr1["OptA"].ToString();
                    B = dr1["OptB"].ToString();
                    C = dr1["OptC"].ToString();
                    D = dr1["OptD"].ToString();
                }
                dr1.Close();
                BtnNext.IsEnabled = true;
                BtnPrevious.IsEnabled = true;
            }
            else if (ClickCount > 1)
            {
                conn = new SqlConnection(connstr);
                conn.Open();
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = new SqlCommand("SELECT Question, Image, OptA, OptB, OptC, OptD FROM Export WHERE QuizNum=@qnum", conn);
                SqlParameter QNum = new SqlParameter();
                da1.SelectCommand.Parameters.AddWithValue("@qnum", qnum);
                SqlDataReader dr1 = da1.SelectCommand.ExecuteReader();

                while (dr1.Read())
                {
                    lblQuiz.Content = "Question " + qnum + ": ";
                    qn = dr1["Question"].ToString();
                    image = dr1["Image"].ToString();
                    A = dr1["OptA"].ToString();
                    B = dr1["OptB"].ToString();
                    C = dr1["OptC"].ToString();
                    D = dr1["OptD"].ToString();
                }
                dr1.Close();
                BtnPrevious.IsEnabled = true;
                BtnNext.IsEnabled = true;
            }

            msgUpdateCompetitor = "@UpdateComp|" + qnum;
            byte[] outStream4 = System.Text.Encoding.ASCII.GetBytes(msgUpdateCompetitor + "#");
            if (serverStream != null)
            {
                serverStream.Write(outStream4, 0, outStream4.Length);
                serverStream.Flush();
            }

            msgToCompetitors = "@SendToComp|Facilitator|" + "Question " + qnum + "|" + connstr + "|" + image + "|" + qn + "|" + A + "|" + B + "|" + C + "|" + D;
            Question.Text = "";
            imageoptA.Source = null;
            imageoptB.Source = null;
            imageoptC.Source = null;
            imageoptD.Source = null;
            imageppt.Source = null;
            cbQn.SelectedIndex = cbQn.Items.IndexOf("Question " + qnum);
            updateScore();
        }

        private void btnOpen2_Click(object sender, RoutedEventArgs e)
        {
            qnum = displayQuestionByComboBox();

            if (CURRENTQNSCOUNT != 0)
            {
                if (MAXQNSCOUNT != -1 && CURRENTQNSCOUNT <= MAXQNSCOUNT)
                {
                    Preview_Time(CURRENTQNSCOUNT.ToString());
                }
            }
            if (qnum == TotalQcount)
            {
                BtnNext.IsEnabled = false;
            }
            else
            {
                BtnNext.IsEnabled = true;
            }

            Question.Text = "";
            imageoptA.Source = null;
            imageoptB.Source = null;
            imageoptC.Source = null;
            imageoptD.Source = null;
            imageppt.Source = null;
            updateScore();
        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            bool containsVulgar = false;
            List<String> vulgarList = new List<String>();
            char[] vulgarArray = null;

            if (tbxmsg.Text != "")
            {
                try
                {
                    SqlConnection conn = new SqlConnection(connstr);
                    conn.Open();
                    SqlCommand comm = new SqlCommand();
                    comm.Connection = conn;
                    comm.CommandText = "SELECT words from Profanity";
                    SqlDataReader dr = comm.ExecuteReader();
                    while (dr.Read())
                    {
                        vulgarList.Add(dr["words"].ToString());
                    }
                    dr.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to establish connection to database");
                }

                finally
                {
                    if (vulgarList.Count != 0)
                    {
                        foreach (String vulgar in vulgarList)
                        {
                            vulgarArray = tbxmsg.Text.ToCharArray();
                            for (int i = 0; i < vulgarArray.Length; i++)
                            {
                                //vulgarArray[i] is from readData = what i have typed
                                //eg if S == S, have to make it lowercase
                                if (vulgarArray[i] == char.ToUpper(vulgarArray[i]))
                                {
                                    vulgarArray[i] = char.ToLower(vulgarArray[i]);
                                }
                            }
                            String vulgarString = new String(vulgarArray); //convert the array back to String for checking
                            if (vulgarString.Contains(vulgar) == true)
                            {
                                containsVulgar = true;
                                break;
                            }
                        }

                    }
                }

                if (containsVulgar == true)
                {
                    const string warning = "Please refrain from using foul language";
                    MessageBoxResult result = MessageBox.Show(warning);
                }

                else if (containsVulgar == false)
                {
                    //send it over to competitor side
                    string msg2 = "@Talk|" + tbxmsg.Text;
                    byte[] outStream = System.Text.Encoding.ASCII.GetBytes(msg2 + "#");
                    if (serverStream != null)
                    {
                        serverStream.Write(outStream, 0, outStream.Length);
                        serverStream.Flush();
                    }
                }
                tbxmsg.Clear();
            }
            else
            {
                MessageBox.Show("Please Type a Message!", "Notification", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void restartTimer()
        {
            string min = lblMin.Content.ToString();
            string sec = lblSec.Content.ToString();
            timer1.Start();

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes("@time|" + min + "|" + sec + "#");
            if (serverStream != null)
            {
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
            }
            paused = false;
            pauseFalse = true;
            PauseBtn.IsEnabled = true;
            PlayBtn.IsEnabled = false;
            StopBtn.IsEnabled = true;
            btnA.IsEnabled = false;
            RestartBtn.IsEnabled = true;

            try
            {
                minutes = Convert.ToInt32(lblMin.Content);
                seconds = Convert.ToInt32(lblSec.Content);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void PlayBtn_Click(object sender, RoutedEventArgs e)
        {
            StartQuizCountdowncs form = new StartQuizCountdowncs();
            form.Show();
            
            string min = lblMin.Content.ToString();
            string sec = lblSec.Content.ToString();     
         
            // to stop facil timer from ticking 1 sec faster
            paused = false;
            pauseFalse = true;
            PauseBtn.IsEnabled = true;
            PlayBtn.IsEnabled = false;
            StopBtn.IsEnabled = true;
            btnA.IsEnabled = false;
            RestartBtn.IsEnabled = true;

            try
            {
                minutes = Convert.ToInt32(lblMin.Content);
                seconds = Convert.ToInt32(lblSec.Content);
                Question.Text = qn;

                if (image != "  ")
                {
                    BitmapImage src = new BitmapImage();
                    src.BeginInit();
                    //src.UriSource = new Uri(image, UriKind.Relative);
                    src.UriSource = new Uri("C:\\Images\\" + image, UriKind.Relative);
                    //getim = ("C:\\Images\\" + image);
                    src.CacheOption = BitmapCacheOption.OnLoad;
                    src.EndInit();
                    imageppt.Source = src;
                }
                else
                {
                    imageppt.Source = null;
                    //getim = null;
                }

                FileInfo file = new FileInfo(A);
                string extension = file.Extension;
                if (extension == ".jpg" || extension == ".png")
                {
                    BitmapImage src2 = new BitmapImage();
                    src2.BeginInit();
                    //src.UriSource = new Uri(image, UriKind.Relative);
                    src2.UriSource = new Uri("C:\\Images\\" + A, UriKind.Relative);
                    //getim = ("C:\\Images\\" + A);
                    src2.CacheOption = BitmapCacheOption.OnLoad;
                    src2.EndInit();
                    imageoptA.Source = src2;
                    LabA.Text = "A) ";
                }
                else
                {
                    LabA.Text = "A) " + A;
                    imageoptA.Source = null;
                    //getim = null;
                }

                FileInfo fileB = new FileInfo(B);
                string extensionB = fileB.Extension;
                if (extensionB == ".jpg" || extensionB == ".png")
                {
                    BitmapImage srcB = new BitmapImage();
                    srcB.BeginInit();
                    //src.UriSource = new Uri(image, UriKind.Relative);
                    srcB.UriSource = new Uri("C:\\Images\\" + B, UriKind.Relative);
                    //getim = ("C:\\Images\\" + B);
                    srcB.CacheOption = BitmapCacheOption.OnLoad;
                    srcB.EndInit();
                    imageoptB.Source = srcB;
                    LabB.Text = "B) ";
                }
                else
                {
                    LabB.Text = "B) " + B;
                    imageoptB.Source = null;
                    //getim = null;
                }

                FileInfo fileC = new FileInfo(C);
                string extensionC = fileC.Extension;
                if (extensionC == ".jpg" || extensionC == ".png")
                {
                    BitmapImage srcC = new BitmapImage();
                    srcC.BeginInit();
                    //src.UriSource = new Uri(image, UriKind.Relative);
                    srcC.UriSource = new Uri("C:\\Images\\" + C, UriKind.Relative);
                    //getim = ("C:\\Images\\" + C);
                    srcC.CacheOption = BitmapCacheOption.OnLoad;
                    srcC.EndInit();
                    imageoptC.Source = srcC;
                    LabC.Text = "C) ";
                }
                else
                {
                    LabC.Text = "C) " + C;
                    imageoptC.Source = null;
                    //getim = null;
                }

                FileInfo fileD = new FileInfo(D);
                string extensionD = fileD.Extension;
                if (extensionD == ".jpg" || extensionD == ".png")
                {
                    BitmapImage srcD = new BitmapImage();
                    srcD.BeginInit();
                    //src.UriSource = new Uri(image, UriKind.Relative);
                    srcD.UriSource = new Uri("C:\\Images\\" + D, UriKind.Relative);
                    //getim = ("C:\\Images\\" + D);
                    srcD.CacheOption = BitmapCacheOption.OnLoad;
                    srcD.EndInit();
                    imageoptD.Source = srcD;
                    LabD.Text = "D) ";
                }
                else
                {
                    LabD.Text = "D) " + D;
                    imageoptD.Source = null;
                    //getim = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //}
        //    else
        //    {
        //        string min = lblMin.Content.ToString();
        //        string sec = lblSec.Content.ToString();

        //        byte[] outStream = System.Text.Encoding.ASCII.GetBytes("@resumePause|" + resumePause + "#");
        //        if (serverStream != null)
        //        {
        //            serverStream.Write(outStream, 0, outStream.Length);
        //            serverStream.Flush();
        //        }

        //        timer1.Start();
        //        paused = false;
        //        PlayBtn.IsEnabled = false;
        //        PauseBtn.IsEnabled = true;
        //        StopBtn.IsEnabled = true;

        //        btnA.IsEnabled = false;
        //        BtnPrevious.IsEnabled = false;
        //        BtnNext.IsEnabled = false;
        //        try
        //        {
        //            minutes = Convert.ToInt32(lblMin.Content);
        //            seconds = Convert.ToInt32(lblSec.Content);
        //        }
        //        catch (Exception ex)
        //        {
        //            MessageBox.Show(ex.Message);
        //        }
        //    }
        //}

        //<resume button method>
        //start timer
        //rectangle invisible
        //resume button invisible

        private void PauseBtn_Click(object sender, RoutedEventArgs e)
        {
            timer1.Stop();
            pauseScreen.Visibility = System.Windows.Visibility.Visible;
            resumebtn.Visibility = System.Windows.Visibility.Visible;
            //some resume button visible
            string min = lblMin.Content.ToString();
            string sec = lblSec.Content.ToString();

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes("@pause|" + min + "|" + sec + "#");
            if (serverStream != null)
            {
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
            }
            // Pause the timer.

            pauseFalse = true;
            paused = true;
            btnA.IsEnabled = false;
            PauseBtn.IsEnabled = false;
            PlayBtn.IsEnabled = true;
            StopBtn.IsEnabled = true;
            try
            {
                minutes = Convert.ToInt32(lblMin.Content);
                seconds = Convert.ToInt32(lblSec.Content);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (last5audioplay == true)
            {
                player.Stop();
            }
        }

        private void StopBtn_Click(object sender, RoutedEventArgs e)
        {
            BtnNext.IsEnabled = false;
            BtnPrevious.IsEnabled = false;
            btnOpen2.IsEnabled = false;
            timer1.Stop();

            string min = lblMin.Content.ToString();
            string sec = lblSec.Content.ToString();

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes("@stop|" + min + "|" + sec + "#");
            if (serverStream != null)
            {
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
            }

            pauseFalse = true;
            paused = false;
            PauseBtn.IsEnabled = false;
            PlayBtn.IsEnabled = false;
            StopBtn.IsEnabled = false;
            btnA.IsEnabled = true;
            RestartBtn.IsEnabled = false;

            try
            {
                minutes = Convert.ToInt32(lblMin.Content);
                seconds = Convert.ToInt32(lblSec.Content);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (last5audioplay == true)
            {
                player.Stop();
            }
        }

        private void BtnScore_Click(object sender, RoutedEventArgs e)
        {
            ScoreBoard window = new ScoreBoard();
            window.Show();
            window.ResizeMode = ResizeMode.NoResize;
        }

        private void Page_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F5)
            {
                e.Handled = true;
            }
            else if (e.Key == Key.Back)
            {
                if (tbxmsg.Text != "")
                {
                    e.Handled = false;
                }
                else
                {
                    e.Handled = true;
                }
            }
        }

        private void tbxmsg_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnSend_Click(this, new RoutedEventArgs());
            }
        }

        private void resumebtn_Click(object sender, RoutedEventArgs e)
        {
            //edited by uni 29/1 4.01pm :)
            //if (paused != true)
            pauseScreen.Visibility = System.Windows.Visibility.Hidden;
            resumebtn.Visibility = System.Windows.Visibility.Hidden;
            timer1.Start();

            string min = lblMin.Content.ToString();
            string sec = lblSec.Content.ToString();

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes("@resumePause|" + resumePause + "#");
            if (serverStream != null)
            {
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
            }
            // Resume the timer.
            //edited by uni 29/1 4.01pm :)

            paused = false;
            PauseBtn.IsEnabled = true;
            PlayBtn.IsEnabled = false;
            StopBtn.IsEnabled = true;


            try
            {
                minutes = Convert.ToInt32(lblMin.Content);
                seconds = Convert.ToInt32(lblSec.Content);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void RestartBtn_Click(object sender, RoutedEventArgs e)
        {
            Preview_Time(qnum);
            BtnNext.IsEnabled = false;
            BtnPrevious.IsEnabled = false;
            btnOpen2.IsEnabled = false;
            restartTimer();
            paused = false;
            btnA.IsEnabled = false;
            PauseBtn.IsEnabled = true;
            PlayBtn.IsEnabled = false;
            StopBtn.IsEnabled = true;

            try
            {
                SqlConnection conn = new SqlConnection(connstr);
                conn.Open();
                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                comm.CommandText = "Delete FROM AlgoLogicDB.dbo.Result WHERE QuizNum=@QuizNum ";
                comm.Parameters.AddWithValue("@QuizNum", CURRENTQNSCOUNT);
                comm.ExecuteNonQuery();
                conn.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            finally
            {
                MessageBox.Show("Time restarted. All submitted options are removed.");
            }
        }

        private void btnLoadQuestions_Click(object sender, RoutedEventArgs e)
        {
            qnum = displayQuestion();

            if (CURRENTQNSCOUNT != 0)
            {
                if (MAXQNSCOUNT != -1 && CURRENTQNSCOUNT <= MAXQNSCOUNT)
                {
                    Preview_Time(CURRENTQNSCOUNT.ToString());
                }
            }

            Question.Text = "";
            imageoptA.Source = null;
            imageoptB.Source = null;
            imageoptC.Source = null;
            imageoptD.Source = null;
            imageppt.Source = null;
            cbQn.SelectedIndex = cbQn.Items.IndexOf("Question " + qnum);
        }
    }
}